//
//  ViewController.m
//  19-json网易
//
//  Created by dllo on 16/8/9.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ViewController.h"
#import "NewsTitle.h"
#import "SCjCollectionViewLayout.h"
#import "TitleCollectionViewCell.h"
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,SCjCollectionViewLayoutDelegate>
@property (nonatomic,strong) NSMutableArray<NewsTitle *> *newsTitleArray;

@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    SCjCollectionViewLayout *layout = (SCjCollectionViewLayout *)self.myCollectionView.collectionViewLayout;
    layout.delegate = self;
//    
//     [_myCollectionView registerNib:[UINib nibWithNibName:@"TitleCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"guobao"];
//    
    [self handleData];
    
}

- (void)handleData
{
    //    缩写都得大写
    NSString *newsJSON = [[NSBundle mainBundle] pathForResource:@"news" ofType:@"json"];
    
    NSData *JSONData = [NSData dataWithContentsOfFile:newsJSON];
    //    JSON解析
    NSError *error = nil;
    NSDictionary *JSONDic = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
    NSArray *arr = JSONDic[@"tList"];
    _newsTitleArray = [NSMutableArray array];
    for (NSDictionary *dic in arr) {
        NewsTitle *newsTitle = [NewsTitle newTitleWithDic:dic];
        [_newsTitleArray addObject:newsTitle];
    }
    NSLog(@"%@", _newsTitleArray);
    
    
    
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    
    return _newsTitleArray.count;
}

//self是get方法
//_是成员变量

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
     TitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.Label1.text = (NSString *)_newsTitleArray[indexPath.row].tname;
    return cell;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
                   height:(CGFloat)height
   sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NewsTitle *title = _newsTitleArray[indexPath.row];
    CGRect newRect = [title.tname boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, _myCollectionView.bounds.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
    CGFloat width = ceilf(CGRectGetWidth(newRect));
    return width;
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
